﻿package extremefx.i18n {
	import extremefx.DateTime;	

	/**
	 * @author Marcelo Volmaro
	 */
	internal final class GregorianEraHandler {
		private var _eras:Array;
		
		public function GregorianEraHandler() {
			_eras = [];
		}

		internal function appendEra(pNr:int, pStart:int, pEnd:int = -1):void {
			if (pEnd == -1) pEnd = CCFixed._fromDateTime(DateTime.MAX_VALUE);
			_eras[pNr] = new GregorianEra(pNr, pStart, pEnd);
		}
		
		internal function gregorianYear(pYear:int, pEra:int):int {
			return GregorianEra(_eras[pEra]).gregorianYear(pYear);
		}
		
		/**
		 * @return an array containing [year of the era, era number]
		 */
		internal function eraYear(pEra:Array, pDate:int):int {
			for each(var e:GregorianEra in _eras) {
				if (e.covers(pDate)) return e.eraYear(pEra, pDate);
			}
	
			throw new RangeError("pDate", "Time value was out of era range.");
		}
		
		internal function checkDateTime(pTime:DateTime):void {
			if (!validDate(CCFixed._fromDateTime(pTime))) throw new RangeError("pTime", "Time value was out of era range.");
		}
		
		internal function validDate(pDate:int):Boolean {
			for each(var e:GregorianEra in _eras) {
				if (e.covers(pDate)) return true;
			}
			return false;
		}
		
		internal function validEra(pEra:int):Boolean {
			return _eras[pEra] is GregorianEra;
		}

		internal function get eras():Array {
			var a:Array = [];
			var e:GregorianEra;
			var i:int = 0;
			while (e = _eras[i++]){
				a.push(e.nr);
			}

			return a;
		}
	}
}
